package com.pfzy.lib.net.utils;

import android.net.Uri;
import android.text.TextUtils;

import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okio.Buffer;

public class ParamsUtils {
    public static String getUrlPath(String strURL) {
        if (TextUtils.isEmpty(strURL)) {
            return "";
        }
        return strURL.trim().split("[?]")[0];
    }

    public static boolean isFilePart(String cdHead) {
        return !TextUtils.isEmpty(cdHead) && cdHead.contains("filename");
    }

    public static String getParamsKeyFromCDHeader(String cdHeader) {
        Pattern pattern = Pattern.compile("name=\"(.*?)\"");
        Matcher matcher = pattern.matcher(cdHeader);
        return matcher.find() ? matcher.group(1) : "";
    }

    public static String getUrlParamsFromMap(Map<String, String> requestParams) {
        if (requestParams == null || requestParams.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : requestParams.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        return sb.substring(0, sb.length() - 1).toString();
    }

    public static String getMD5(String source) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.update(source.getBytes("UTF-8"));
            byte[] hash = md5.digest();
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xff) < 16) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xff));
            }
            return hex.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        } catch (Exception e2) {
            e2.printStackTrace();
            return "";
        }
    }

    public static Class<?> getRawType(Type type) {
        if (type instanceof Class) {
            return (Class) type;
        }
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Type rawType = parameterizedType.getRawType();
            checkArgument(rawType instanceof Class);
            return (Class) rawType;
        } else if (type instanceof GenericArrayType) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            return Array.newInstance(getRawType(componentType), 0).getClass();
        } else if (type instanceof TypeVariable) {
            return Object.class;
        } else {
            if (type instanceof WildcardType) {
                return getRawType(((WildcardType) type).getUpperBounds()[0]);
            }
            String className = type == null ? "null" : type.getClass().getName();
            throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
        }
    }

    public static void checkArgument(boolean condition) {
        if (!condition) {
            throw new IllegalArgumentException();
        }
    }

    public static String decode(String encoded) {
        return percentDecode(encoded, 0, encoded.length(), true);
    }

    public static String percentDecode(String encoded, int pos, int limit, boolean plusIsSpace) {
        for (int i = pos; i < limit; i++) {
            char c2 = encoded.charAt(i);
            if (c2 == '%' || (c2 == '+' && plusIsSpace)) {
                Buffer out = new Buffer();
                out.writeUtf8(encoded, pos, i);
                percentDecode(out, encoded, i, limit, plusIsSpace);
                return out.readUtf8();
            }
        }
        return encoded.substring(pos, limit);
    }

    static void percentDecode(Buffer out, String encoded, int pos, int limit, boolean plusIsSpace) {
        int i = pos;
        while (i < limit) {
            int codePoint = encoded.codePointAt(i);
            if (codePoint == 37 && i + 2 < limit) {
                int d1 = decodeHexDigit(encoded.charAt(i + 1));
                int d2 = decodeHexDigit(encoded.charAt(i + 2));
                if (d1 != -1 && d2 != -1) {
                    out.writeByte((d1 << 4) + d2);
                    i += 2;
                }
                out.writeUtf8CodePoint(codePoint);
            } else {
                if (codePoint == 43 && plusIsSpace) {
                    out.writeByte(32);
                }
                out.writeUtf8CodePoint(codePoint);
            }
            i += Character.charCount(codePoint);
        }
    }

    public static boolean needAdd(String host, ArrayList validHosts, ArrayList invalidHosts) {
        if(TextUtils.isEmpty(host)) {
            return false;
        }

        if(validHosts != null && validHosts.size() > 0) {
            Iterator iterator = validHosts.iterator();
            while(iterator.hasNext()){
                Object url = iterator.next();
                String urlHost = Uri.parse(((String)url)).getHost();
                if(!TextUtils.isEmpty(urlHost)) {
                    if(host.equals(urlHost)) {
                        return true;
                    }
                }
            }
            return false;
        }

        if(invalidHosts != null && invalidHosts.size() > 0) {
            Iterator iterator = invalidHosts.iterator();
            while (iterator.hasNext()){
                Object url = iterator.next();
                String urlHost = Uri.parse(((String)url)).getHost();
                if(!TextUtils.isEmpty(urlHost)) {
                    if(host.equals(urlHost)) {
                        return true;
                    }
                }
            }
            return false;
        }

        return false;
    }

    public static int decodeHexDigit(char c2) {
        if (c2 < '0' || c2 > '9') {
            if (c2 >= 'a' && c2 <= 'f') {
                return (c2 - 'a') + 10;
            }
            if (c2 >= 'A' && c2 <= 'F') {
                return (c2 - 'A') + 10;
            }
            return -1;
        }
        return c2 - '0';
    }
}
